package com.mindai.esper.monitor.biz.epl;

import com.espertech.esper.client.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
 * Created by Ladd on 16-6-30.
 */
@Slf4j
@Data
@Service
public class EsperEplService implements Serializable {


    @Autowired
    CommonEsperEplService commonEsperEplService;

    private EPAdministrator admin = null;
    private EPRuntime runtime = null;
    private EPServiceProvider epService = null;
    private Configuration configuration = null;

    private boolean loadFlag = false;

    /**
     * 执行RunEpl表达式
     */
    public void runEpl() {

        //1 创建一个 Configuration 配置
        this.configuration = new Configuration();
        //暂时不清楚该配置项的使用逻辑，先注释掉
        //this.configuration.getEngineDefaults().getThreading().setInsertIntoDispatchPreserveOrder(false);
        commonEsperEplService.addMethods();
        commonEsperEplService.addEsperDb();

        //2、通过 EPServiceProviderManager通过参数configuration,获得EPServiceProvider(引擎实例epService);
        this.epService = EPServiceProviderManager.getDefaultProvider(configuration);

        //3、通过 EPServiceProvider 获得 EPAdministrator 对象;
        this.admin = epService.getEPAdministrator();
        //4、通过 EPAdministrator 和 EPL 查询语句，创建 EPStatement
        commonEsperEplService.addSchemas(admin);
        commonEsperEplService.addEsperEpl(admin);

        this.runtime = epService.getEPRuntime();
        //初始化
        loadFlag = true;
    }

    /**
     * 判断是否已经启动
     * @return
     */
    public boolean isLoad(){
        return this.loadFlag;
    }
}
